package com.smartstate.iot.service;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.smartstate.iot.config.SpringBeanUtils;
import com.smartstate.iot.config.web.SpringUtils;
import com.smartstate.iot.entity.TopicConfig;
import com.smartstate.iot.mapper.TopicMapper;
import com.smartstate.iot.mqtt.client.MyMQTTClient;
import com.smartstate.iot.mqtt.common.GlobalMqttParam;
import com.smartstate.iot.service.impl.DataDistributionServiceImpl;
import com.smartstate.iot.vo.TopicUpVo;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class TransmitThreadService implements Runnable {

    @Autowired
    private TopicMapper mapper;

    GlobalMqttParam globalMqttParam = SpringUtils.getBean(GlobalMqttParam.class);
    String broker = globalMqttParam.getBroker();
    String userName = globalMqttParam.getUserName();
    String passWord = globalMqttParam.getPassWord();
    String clientId1 = globalMqttParam.getSubClientId1() + new DateTime();
    int keepalive = globalMqttParam.getKeepalive();
    int timeout = globalMqttParam.getTimeout();
    MyMQTTClient myMQTTClient = new MyMQTTClient(broker, userName, passWord, clientId1, keepalive, timeout);

    String topic;
    String msg;

    public TransmitThreadService(String topic, String msg) {
        this.topic = topic;
        this.msg = msg;
    }

    @Override
    public void run() {
        TopicUpVo topicUpVo = new TopicUpVo();
        topicUpVo.setConfig("true");
        long time = new Date().getTime();
        topicUpVo.setTimesTamp(String.valueOf(time));
        JSONArray jsonArray = JSON.parseArray(msg);
        List<TopicUpVo.Content> contents = groupContent(jsonArray);
        topicUpVo.setContent(contents);
//              中台下发的消息，发送给盒子
        try {
            myMQTTClient.connect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
        myMQTTClient.publish(JSON.toJSONString(topicUpVo), topic, 2, false);
        log.info("转发配置成功！");
    }
    public List<TopicUpVo.Content> groupContent(JSONArray list) {
        List<TopicUpVo.Content> contents = new ArrayList<TopicUpVo.Content>();
        DataDistributionServiceImpl distributionService = SpringBeanUtils.getBean(DataDistributionServiceImpl.class);
        ArrayList<String> keys = distributionService.getKeys();
        loop:
        for (Object o : list) {
            TopicUpVo.ConfigDetails configDetails = JSON.parseObject(o.toString(), TopicUpVo.ConfigDetails.class);
            String dataId = configDetails.getDataId();
            int index = dataId.indexOf(".");
            String deviceName = dataId.substring(0, index);
            for (String key : keys) {
                if (key.endsWith(deviceName)) {
                    TopicUpVo.Content content = new TopicUpVo.Content();
                    int indexOf = key.indexOf(":");
                    String deviceId = key.substring(0,indexOf);
                    TopicMapper mapper = SpringBeanUtils.getBean(TopicMapper.class);
                    TopicConfig topicConfig = mapper.getByDeviceId(deviceId);
                    if (contents.size() != 0) {
                        for (TopicUpVo.Content content1 : contents) {
                            if (content1.getDeviceId().equals(topicConfig.getDeviceId())) {
                                List<TopicUpVo.ConfigDetails> config = content1.getConfig();
                                config.add(configDetails);
                                continue loop;
                            }
                        }
                        addNewContent(contents, configDetails, content, topicConfig);
                    } else {
                        addNewContent(contents, configDetails, content, topicConfig);
                    }
                    break;
                }
            }
        }
        return contents;
    }

    private void addNewContent(List<TopicUpVo.Content> contents, TopicUpVo.ConfigDetails configDetails, TopicUpVo.Content content, TopicConfig topicConfig) {
        content.setDeviceId(topicConfig.getDeviceId());
        content.setDeviceName(topicConfig.getDeviceName());
        content.setIp(topicConfig.getIp());
        content.setPort(topicConfig.getPort());
        content.setCpu(topicConfig.getCpu());
        content.setNewTopic(topicConfig.getNewTopic());
        content.setMomery(topicConfig.getMomery());
        ArrayList<TopicUpVo.ConfigDetails> details = new ArrayList<>();
        details.add(configDetails);
        content.setConfig(details);
        contents.add(content);
    }
}
